"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = useHooks;

var _antd = require("antd");

var _x10 = require("@antv/x6");

var _tools = require("./tools");

var _react = _interopRequireDefault(require("react"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

var {
  Dragger
} = _antd.Upload; // 文件解析

var fileExplain = file => {
  var reader = new FileReader();
  reader.readAsText(file);

  reader.onload = /*#__PURE__*/function () {
    var _ref = _asyncToGenerator(function* (event) {
      _antd.Modal.destroyAll();

      try {
        var _event$target;

        var jsonData = JSON.parse(((_event$target = event.target) === null || _event$target === void 0 ? void 0 : _event$target.result) || '[]');

        _antd.message.success('文件解析完成');

        yield (0, _tools.autoSaveJson)(jsonData, null);
        window.location.reload();
      } catch (e) {
        _antd.message.error('文件解析失败');
      }
    });

    return function (_x) {
      return _ref.apply(this, arguments);
    };
  }();

  _antd.Modal.info({
    closable: false,
    className: 'rasir-fc-model',
    title: '文件解析',
    content: '文件解析中，请稍等...',
    okButtonProps: {
      disabled: true
    }
  });
};

function useHooks(_ref2) {
  var {
    onRemoveLink,
    onRemoveNode,
    // onAddNode,
    onAddLink,
    onSave
  } = _ref2;
  var actionFunMap = {
    // 编辑节点
    edite: (_, __, config) => {
      var {
        setVisible
      } = config;
      setVisible(true);
    },
    // 删除节点或连线
    delete: (cell, graph) => {
      var cellItems = [];
      if (cell) cellItems = [cell];else {
        // 如果currentCell没有值 就去graph中找有没有被选中的节点
        cellItems = graph.getSelectedCells();
      }

      if (!cellItems.length) {
        _antd.message.info('请先选择要删除的节点', {
          duration: 1000
        });

        return;
      }

      var isNode = cellItems[0].isNode();
      var isEdge = cellItems[0].isEdge();

      if (isNode) {
        _antd.Modal.confirm({
          title: '删除节点',
          className: 'rasir-fc-model',
          content: "\u8BE5\u64CD\u4F5C\u5C06\u5220\u9664\u8282\u70B9 ".concat(cellItems.map(cell => cell.label).join(','), " \u662F\u5426\u7EE7\u7EED\uFF1F"),
          okText: '确定',
          cancelText: '取消',
          centered: true,
          onOk: () => new Promise( /*#__PURE__*/function () {
            var _ref3 = _asyncToGenerator(function* (resolve, reject) {
              if (!onRemoveNode || onRemoveNode && (yield onRemoveNode(cellItems.map(cell => cell.data)))) {
                graph.removeCells(cellItems.map(cell => graph.getCellById(cell.data.id)));
                resolve(1);
              } else reject();
            });

            return function (_x2, _x3) {
              return _ref3.apply(this, arguments);
            };
          }())
        });
      } else if (isEdge) {
        _antd.Modal.confirm({
          title: '删除连线',
          className: 'rasir-fc-model',
          content: "\u8BE5\u64CD\u4F5C\u5C06\u5220\u9664\u8FDE\u7EBF\u662F\u5426\u7EE7\u7EED\uFF1F\u8BF7\u786E\u8BA4",
          okText: '确定',
          cancelText: '取消',
          centered: true,
          onOk: () => new Promise( /*#__PURE__*/function () {
            var _ref4 = _asyncToGenerator(function* (resolve, reject) {
              if (onRemoveLink && !(yield onRemoveLink(cellItems))) {
                reject();
              } else {
                graph.removeCells(cellItems);
                resolve(1);
              }
            });

            return function (_x4, _x5) {
              return _ref4.apply(this, arguments);
            };
          }()),

          onCancel() {
            cellItems.forEach(cellItem => {
              graph.addCell(cellItem);
            });
          }

        });
      }
    },
    // 添加节点或连线
    add: function () {
      var _add = _asyncToGenerator(function* (cellItem, graph) {
        var isEdge = cellItem.isEdge(); // 暂时没用上 后续可优化
        // const isNode = cellItem.isNode();
        // if (isNode) {
        //   message.loading({ duration: 0, content: '节点生成中，请稍等' });
        //   let ret: any;
        //   if (onAddNode) ret = await onAddNode();
        //   message.destroy();
        //   if (onAddNode && !ret) {
        //     graph.removeCell(cellItem);
        //   } else message.success('节点生成成功');
        // } else

        if (isEdge) {
          _antd.message.loading({
            duration: 0,
            content: '连接生成中，请稍等'
          });

          if (!(onAddLink && !(yield onAddLink()))) {
            var {
              source,
              target
            } = cellItem;
            var edgeData = {
              id: "".concat(source.cell, "_").concat(target.cell),
              source: source.cell,
              target: target.cell
            };
            graph.addEdge(_objectSpread({
              shape: 'lane-edge',
              data: _objectSpread(_objectSpread({}, edgeData), {}, {
                type: 'link',
                zIndex: 1
              })
            }, edgeData));

            _antd.message.destroy();

            _antd.message.success('连接成功');
          }
        }
      });

      function add(_x6, _x7) {
        return _add.apply(this, arguments);
      }

      return add;
    }(),
    // 缩小
    smaller: (_, __, _ref5) => {
      var {
        zoom,
        setZoom
      } = _ref5;
      if (zoom <= 0.5) return;
      setZoom(zoom - 0.1);
    },
    // 放大
    bigger: (_, __, _ref6) => {
      var {
        zoom,
        setZoom
      } = _ref6;
      if (zoom >= 1.5) return;
      setZoom(zoom + 0.1);
    },
    // 复制节点
    copy: (_, graph) => {
      var cellItems = graph.getSelectedCells();
      if (!cellItems.length) return _antd.message.info('请先选择要复制的节点');
      if (cellItems.length > 1) return _antd.message.info('一次只能复制一个节点');
      graph.copy(cellItems);

      _antd.message.success('节点成功放入剪贴板');
    },
    // 粘贴节点
    paste: (_, graph, _ref7) => {
      var {
        setVisible,
        setCurrentCell
      } = _ref7;

      if (!graph.isClipboardEmpty()) {
        var [cell] = graph.getCellsInClipboard();
        graph.cleanSelection();
        cell.setData({
          id: null
        }, {
          deep: true
        });
        setCurrentCell(cell);
        (0, _tools.nextTick)(() => setVisible(true));
      } else {
        _antd.message.info('剪贴板中没有节点');
      }
    },
    // 导出图片
    exportImg: (_, graph) => {
      var chartName = undefined;

      _antd.Modal.confirm({
        title: '导出图片',
        className: 'rasir-fc-model',
        cancelText: '取消',
        okText: '确定',
        width: 500,
        onOk: () => new Promise((resolve, reject) => {
          if (!chartName) {
            _antd.message.info('请输入图片名称');

            reject();
          } else {
            graph.toPNG(dataUri => {
              // 下载
              _x10.DataUri.downloadDataUri(dataUri, "".concat(chartName, ".png"));

              resolve(1);
            }, {
              quality: 1,
              padding: {
                top: 20,
                right: 20,
                bottom: 20,
                left: 20
              }
            });
          }
        }),
        content: /*#__PURE__*/_react.default.createElement(_antd.Input, {
          value: chartName,
          onChange: e => chartName = e.target.value,
          placeholder: "\u8BF7\u8F93\u5165\u56FE\u7247\u540D\u79F0"
        })
      });
    },
    // 保存到后端
    save: (_, graph) => {
      if (!onSave) return;

      _antd.Modal.confirm({
        title: '数据上传',
        className: 'rasir-fc-model',
        content: "\u8BE5\u64CD\u4F5C\u5C06\u6570\u636E\u4E0A\u4F20\u5230\u4E91\u7AEF\uFF0C\u8BF7\u786E\u8BA4",
        okText: '确定',
        cancelText: '取消',
        centered: true,
        onOk: () => new Promise( /*#__PURE__*/function () {
          var _ref8 = _asyncToGenerator(function* (resolve, reject) {
            var ret = yield onSave((0, _tools.getGraphJSONData)(graph));

            if (ret) {
              _antd.message.success('上传成功！');

              resolve(1);
            } else {
              reject();
            }
          });

          return function (_x8, _x9) {
            return _ref8.apply(this, arguments);
          };
        }())
      });
    },
    // 导出数据文件
    exportData: (_, graph) => {
      var fileName = '';

      _antd.Modal.confirm({
        title: '导出文件',
        className: 'rasir-fc-model',
        content: /*#__PURE__*/_react.default.createElement("div", null, /*#__PURE__*/_react.default.createElement(_antd.Input, {
          onChange: e => fileName = e.target.value,
          placeholder: "\u8BF7\u8F93\u5165\u6587\u4EF6\u540D\u79F0"
        })),
        okText: '确定',
        cancelText: '取消',
        onOk: () => {
          if (!fileName) {
            _antd.message.error('请输入文件名称');

            return Promise.reject();
          }

          try {
            var content = JSON.stringify((0, _tools.getGraphJSONData)(graph));
            var file = new Blob([content], {
              type: 'application/json'
            });
            var fileUrl = URL.createObjectURL(file);
            var linkElement = document.createElement('a');
            linkElement.setAttribute('href', fileUrl);
            linkElement.setAttribute('download', "".concat(fileName, ".json"));
            linkElement.click();
            return Promise.resolve(1);
          } catch (e) {
            _antd.message.error('数据导出失败');

            return Promise.resolve(1);
          }
        }
      });
    },
    // 导入文件数据
    importData: _ => {
      _antd.Modal.confirm({
        title: '导入数据',
        okText: '确定',
        cancelText: '取消',
        className: 'rasir-fc-model',
        content: /*#__PURE__*/_react.default.createElement(Dragger, {
          action: "/",
          fileList: [],
          beforeUpload: file => {
            _antd.Modal.destroyAll();

            fileExplain(file);
            return Promise.reject();
          }
        }, /*#__PURE__*/_react.default.createElement("p", {
          style: {
            fontSize: 40
          }
        }, "+"), /*#__PURE__*/_react.default.createElement("p", null, "\u8BF7\u9009\u62E9\u8981\u5BFC\u5165\u7684\u6570\u636E"))
      });
    },
    // 清理缓存数据
    clearStorage: _ => {
      _antd.Modal.confirm({
        title: '清理缓存',
        className: 'rasir-fc-model',
        content: "\u8BE5\u64CD\u4F5C\u5C06\u6E05\u7406\u7F13\u5B58\u6570\u636E\uFF0C\u8BF7\u786E\u8BA4",
        okText: '确定',
        cancelText: '取消',
        centered: true,
        onOk: function () {
          var _onOk = _asyncToGenerator(function* () {
            yield (0, _tools.autoSaveJson)(null, null);
            window.location.reload();
          });

          function onOk() {
            return _onOk.apply(this, arguments);
          }

          return onOk;
        }()
      });
    },
    // 全屏
    full: (_, __, _ref9) => {
      var {
        fullContainer,
        setIsFullScreen
      } = _ref9;
      (0, _tools.launchFullScreen)(fullContainer);
      (0, _tools.nextTick)(() => setIsFullScreen(true));
    },
    // 取消全屏
    normal: (_, graph, _ref10) => {
      var {
        setIsFullScreen
      } = _ref10;
      (0, _tools.exitFullscreen)();
      (0, _tools.nextTick)(() => setIsFullScreen(false));
    },
    // 撤销
    undo: (_, graph) => {
      var history = graph.history;
      history.undo();
    },
    // 重做
    redo: (_, graph) => {
      var history = graph.history;
      history.redo();
    }
  };
  return {
    actionFunMap
  };
}